// 查询个人动态


// 获取查看个人动态按钮
var lookPersonDyBtn = document.getElementById("lookPersonDy");

// 获得展示个人动态的盒子
var lookPersonDyBox = document.getElementById("lookPersonDyBox");

// 获取个人所有动态
var personDy = "";

// 获得个人动态的个数
let personDyLen = 0;

let detailPersonDyBtn = "";

// 动态小卡片封面模板字符串
function htmlDyTopP(data){
    var str = '';
 
        str = ` <div class="everyDyBox">
              <div class="Dycover">
                <h3 class="detailDyP">${data.title}</h3>
                <li class="DyCoverContent">${data.content}</li>
                <ul>
                  <li class="DyCoverName"> ${data.username}</li>
                  <li class="userDyTime">发布时间:${switchTimeFormat(data.creationTime)}</li>  
                </ul>
              </div>        
            </div>
            `;
          return str;
    }
    
// 动态详情的模板字符串
function htmlDyDetailP(data){
  var str = '';
  var imgStr ='';
  if(data.hasPicture){
      let imgLen = data.urls.length;
      for(let i = 0 ; i<imgLen ; i++){
        imgStr +=`   <li class="DyImgContent"><img style="width: 250px;height: 250px;" src=${queryURL}${data.urls[i]} alt=""></li>`
      }
      str = ` <div class="everyDyBox">
           
            <div class="everyDy">
              <ul class="userDyInfo">
              <li class="userDyTitle">${data.title}</li>

              </ul>
              <ul class="userDyHeader">
                <li class="DyId">动态ID:${data.id}</li>
                <li class="userDyId">用户ID:${data.userId}</li>
                <li class="userDyname">用户名称:${data.username}</li>
                <li class="userDyTime">发布时间:${switchTimeFormat(data.creationTime)}</li>      
              </ul>
              <ul class="userDyContent">
                <ul class="DyimgBox">
                 ${imgStr}
                </ul>
                <li class="DyTextContent">${data.content}</li>
              </ul>
              <ul class="icoBox">
                <li class="backPerAllDy">
                  <i class="fas fa-reply"></i> 
                </li>
                <li class="delPerAllDy">
                  <i class="fas fa-trash-alt delIco"></i> 
                </li>
              </ul>
            </div>
          </div>
          `;
  }
  else{
      str = `   <div class="everyDyBox">
      <div class="everyDy">
        <ul class="userDyInfo">
        <li class="userDyTitle">${data.title}</li>
        </ul>
        <ul class="userDyHeader">
      
          <li class="DyId">动态ID:${data.id}</li>
          <li class="userDyId">用户ID:${data.userId}</li>
          <li class="userDyname">用户名称:${data.username}</li>
          <li class="userDyTime">发布时间:${switchTimeFormat(data.creationTime)}</li>      
        </ul>
        <ul class="userDyContent">
          <li class="DyTextContent">${data.content}</li>
        </ul>
        <ul class="icoBox">
          <li class="backPerAllDy">
            <i class="fas fa-reply"></i> 
          </li>
          <li class="delPerAllDy">
            <i class="fas fa-trash-alt delIco"></i> 
          </li>
        </ul>
      </div>
    </div>`;
  }
  return str;
}

// 插入动态小卡片封面
function insertPersonDyHtml(value){
  let dyAllContent = "";
              
  personDy = value;
            
  personDyLen = value.data.length;

  for(let i = 0 ; i < personDyLen ; i ++){
      dyAllContent += htmlDyTopP(value.data[i]);
  }
  
  lookPersonDyBox.innerHTML = dyAllContent;
}



// 评论的模板字符串(内含回复，删除，返回，评论功能)
function commentPersonStr(commentArrays,commentOwner){
 
  let comment = `<div class="CommentsBox">
 <li>评论区</li>
  <textarea
  type="text"
  placeholder="请在此处输入评论内容"
  id="newCommentContent"
  name="content"
  style="resize: none; font-size: 18px"
></textarea>
<button  type="button" class="commentBtn">新增评论</button>
</div>
  `;
  lookPersonDyBox.innerHTML += comment;
  let len = commentArrays.length;
  console.log(commentArrays);
// for遍历所有回复评论到页面种
  for(let k = 0 ; k < len ; k++){
   
    if(commentArrays[k].replyId == 0){

      comment = ` 
          <div class="everyCm"> 
            <li class="mainComment"><img id="replyerAvatar" src="${queryURL}${commentArrays[k].replyerPhoto}" alt="">"${commentArrays[k].replyerName}" : ${commentArrays[k].commentsContent} 
            <button type="button" id="replyBtn${commentArrays[k].id}">回复</button> 
            <button type="button" id="commentDelBtn${commentArrays[k].id}">删除</button> 
            </li>
         <div id = "replyBox${commentArrays[k].id}"></div>
          </div>`;
          lookPersonDyBox.innerHTML += comment;
     
    }
    else{
      for(let j = 0 ; j < len ; j++){
        if(commentArrays[k].replyId == commentArrays[j].id){
          comment = ` 
          <div class="everyReply"> 
            <li class="mainComment"><img id="replyerAvatar" src="${queryURL}${commentArrays[k].replyerPhoto}" alt="">"${commentArrays[k].replyerName}"回复<img id="beReplyerAvatar" src="${queryURL}${commentArrays[k].replyerPhoto}" alt="">"${commentArrays[k].beReplyerName}"说 : ${commentArrays[k].commentsContent}
            <button type="button" id="replyBtn${commentArrays[k].id}">回复</button> 
            <button type="button" id="commentDelBtn${commentArrays[k].id}">删除</button> 
            </li>
            <div id = "replyBox${commentArrays[k].id}"></div>
           
          </div>`
          document.getElementById(`replyBox${commentArrays[j].id}`).innerHTML += comment;
        }
      }
     
    }
  }
  // 为删除回复和添加回复按钮绑定事件
  for(let k = 0 ; k < len ; k++){
    let itsId = commentArrays[k].id;
    let ownerId = commentArrays[k].replyerId;
    document.getElementById(`commentDelBtn${itsId}`).onclick = function(){
//  在自己的动态下可以删除别人的评论
        let data = new FormData();
        data.append("id",itsId)
        postForm(data,"comment/delete").then(value=>{
          if(value.code == 200){
            alert("删除评论成功");
            backPerAllBtn.click();
          }
        });
      
     
     
    }
    
    document.getElementById(`replyBtn${itsId}`).onclick = function(){
      if(userInfoG){
        let ipt = prompt("请输入你想要回复的内容:","");
        if(ipt){
          let data = new FormData();
   
          data.append("dynamicStateId",commentArrays[0].dynamicStateId);
          data.append("replyId",itsId);
          data.append("replyerId",window.userInfoG.data.id);
          data.append("beReplyerId",ownerId);
          data.append("commentsContent",ipt);
          postForm(data,"comment/reply").then(value=>{
            if(value.code == 200){
              alert(value.msg);
              backPerAllBtn.click();
            }
          },reason=>{
            alert("是否格式不对")
          })
        }
        else{
          alert("内容为空");
        }
      }
      else{
        alert("请先登陆!");
      }
    }

  }

  // 为返回按钮绑定事件
  let backPerAllBtn = document.querySelector(".backPerAllDy");    
        backPerAllBtn.onclick = function(){
          let urls = "dynamicState/select/" + window.userInfoG.data.id;
          pathGetData(urls).then(function(value){
              if(value.code == 200){
                  console.log(value);
                  console.log(value.msg);
      
                  insertPersonDyHtml(value);
      
                  let detailPersonDyBtn = document.getElementsByClassName("detailDyP");
      
              
                  toPersonDetailDy(detailPersonDyBtn);


                  if(isNight){
                    nightBtn.click();
                  }
                  else{
                    sunBtn.click();
                  }
              }
              else if(value.code == 11000){
                  alert("查询结果为空");
              }
              else{
         
                  alert("后台可能炸了？");
              }
          },function(reason){alert("AJAX请求失败")});
        }

  let delPerDyBtn = document.querySelector(".delPerAllDy");
        delPerDyBtn.onclick = function(){
          if(confirm("是否要删除该动态")){

            let data = new FormData();
            //数据类型转化，如果输入非数字，得到NaN
          
            data.append("id",commentArrays[0].dynamicStateId);
        
            postForm(data,"dynamicState/delete").then(
                value=>{
                    if(value.code == 200){
                        console.log(value.msg);
                     
                        lookPersonDy.click();
                    }
                    else if(value.code == 500){
                        console.log(value.msg);
                    }
                    else{
                        alert("后台又又又炸掉了！");
                    }
                },
                reason=>{
                }
            ) 

            
          }
        
        }


  //  为发表新评论按钮绑定事件
  let newCommentBtn = document.querySelector(".commentBtn");
  newCommentBtn.onclick = function(){
    if(userInfoG){
      let ipt = document.getElementById("newCommentContent").value;
      let data = new FormData();
   
      data.append("dynamicStateId",commentArrays[0].dynamicStateId);
      data.append("replyerId",window.userInfoG.data.id);
      data.append("beReplyerId",commentOwner);
      data.append("commentsContent",ipt);
      if(ipt){
        postForm(data,"comment/insert").then(function(value){
          if(value.code == 200){
            alert("发表评论成功");
            backPerAllBtn.click();
          }
        },function(reason){
          alert("请检查格式!")
        })
      }
      else{
        alert("您暂未输入任何内容!");
      }
    }
    else{
      alert("请先登陆!");
    }
   

  } 
  
}

// 当没有评论时开辟评论区的一个函数
function firstPersonComment(dyId,commentOwner){
  let comment = `<div class="CommentsBox">
  <li>评论区</li>
  <textarea
  type="text"
  placeholder="请在此处输入评论内容"
  id="newCommentContent"
  name="content"
  style="resize: none; font-size: 18px"
></textarea>
  <button  type="button" class="commentBtn">新增评论</button>
  </div>
  `;
  lookPersonDyBox.innerHTML += comment;

   // 为返回按钮绑定事件
   let backPerAllBtn = document.querySelector(".backPerAllDy");    
   backPerAllBtn.onclick = function(){
     let urls = "dynamicState/select/" + window.userInfoG.data.id;
     pathGetData(urls).then(function(value){
         if(value.code == 200){
             console.log(value);
             console.log(value.msg);
 
             insertPersonDyHtml(value);
 
             let detailPersonDyBtn = document.getElementsByClassName("detailDyP");
 
         
             toPersonDetailDy(detailPersonDyBtn);

             if(isNight){
              nightBtn.click();
            }
            else{
              sunBtn.click();
            }
         }
         else if(value.code == 11000){
             alert("查询结果为空");
         }
         else{
    
             alert("后台可能炸了？");
         }
     },function(reason){alert("AJAX请求失败")});
   }
  //  为发表新评论按钮绑定事件
  let newCommentBtn = document.querySelector(".commentBtn");
  newCommentBtn.onclick = function(){
    if(userInfoG){
    let ipt = document.getElementById("newCommentContent").value;
    let data = new FormData();
      
    data.append("dynamicStateId",dyId);
    data.append("replyerId",window.userInfoG.data.id);
    data.append("beReplyerId",commentOwner);
    data.append("commentsContent",ipt);
      if(ipt){
        postForm(data,"comment/insert").then(function(value){
          if(value.code == 200){
            alert("发表评论成功");
            backPerAllBtn.click();
          }
        },function(reason){
          alert("请检查格式!")
        })
      }
      else{
        alert("您暂未输入任何内容!");
      }
    }
    else{
    alert("请先登陆!");
    }


  } 

  let delPerDyBtn = document.querySelector(".delPerAllDy");
  delPerDyBtn.onclick = function(){
    if(confirm("是否删除该动态")){

      let data = new FormData();
      //数据类型转化，如果输入非数字，得到NaN
    
      data.append("id",dyId);
  
      postForm(data,"dynamicState/delete").then(
          value=>{
              if(value.code == 200){
                  console.log(value.msg);
               
                  lookPersonDy.click();
              }
              else if(value.code == 500){
                  console.log(value.msg);
              }
              else{
                  alert("后台又又又炸掉了！");
              }
          },
          reason=>{
          }
      ) 

    }

    
  }
}


function getPersonCommentText(dyId,userId){
  
  let data = new FormData();
  data.append("dynamicId",dyId);
  postForm(data,"getReplyById").then(value=>{
    if(value.code == 1000){
 
      
      commentPersonStr(value.data,userId);
    }
    else if(value.code == 1001){
      firstPersonComment(dyId,userId);
    }
  },reason=>{
    alert("发送请求失败，请检查输入格式")
  })


}

// 为了实现实时刷新而定义的函数
function toPersonDetailDy(detailPersonDyBtn){

    if(personDy){
        for(let i = 0 ; i< personDyLen ; i++){
            detailPersonDyBtn[i].onclick=function(){
              let str = htmlDyDetailP(personDy.data[i]);
         
              lookPersonDyBox.innerHTML = str;
            
              getPersonCommentText(personDy.data[i].id,personDy.data[i].userId);
            
            }
        }  
    }
    else{
     alert("您暂未发布个人动态");
    }     
    
}





// 为查看个人动态绑定事件
lookPersonDyBtn.onclick = function(){
  trunBackDyBtn.click();
  searchDyWrapper.style.display = "none";
    AllDyWapper.style.display = "none";
    lookPersonDyBox.style.display = "flex";
    let urls = "dynamicState/select/" + window.userInfoG.data.id;
    pathGetData(urls).then(function(value){
        if(value.code == 200){
            console.log(value);
            console.log(value.msg);

            insertPersonDyHtml(value);

            let detailPersonDyBtn = document.getElementsByClassName("detailDyP");

        
            toPersonDetailDy(detailPersonDyBtn);

            if(isNight){
              nightBtn.click();
            }
            else{
              sunBtn.click();
            }
        }
        else if(value.code == 11000){
          str = `<div style="margin:20px auto;">该用户暂时没有动态，快去发布一个吧</div>`
          lookPersonDyBox.innerHTML = str;
        }
        else{
   
            alert("后台可能炸了？");
        }
    },function(reason){alert("AJAX请求失败")});
}